import React, { useState, useEffect } from 'react';
import { message } from 'antd';
import PlanInfo from './components/PlanInfo';
import PlanTable from './components/PlanTable';
import ActionButtons from './components/ActionButtons';
import { fetchPlanData, savePlanSummary, submitPlanForReview } from './service';
import { PlanData } from './types';
import styles from './index.less';

const Pg4: React.FC = () => {
  const [planData, setPlanData] = useState<PlanData | null>(null);
  const [summary, setSummary] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    // 获取投产规划数据
    const loadData = async () => {
      try {
        setLoading(true);
        const data = await fetchPlanData();
        setPlanData(data);
        setSummary(data.planInfo.summary);
        setLoading(false);
      } catch (error) {
        message.error('获取投产规划信息失败');
        setLoading(false);
      }
    };

    loadData();
  }, []);

  // 处理摘要变更
  const handleSummaryChange = (value: string) => {
    setSummary(value);
  };

  // 处理保存按钮点击
  const handleSave = async () => {
    try {
      setLoading(true);
      await savePlanSummary(summary);
      message.success('保存成功');
      setLoading(false);
    } catch (error) {
      message.error('保存失败');
      setLoading(false);
    }
  };

  // 处理送审按钮点击
  const handleSubmit = async () => {
    try {
      setLoading(true);
      await submitPlanForReview(summary);
      message.success('送审成功');
      setLoading(false);
    } catch (error) {
      message.error('送审失败');
      setLoading(false);
    }
  };

  // 处理关闭按钮点击
  const handleClose = () => {
    // 这里可以通过路由返回上一页或关闭当前页面
    window.history.back();
  };

  return (
    <div className={styles['modal-container']}>
      <div className={styles['modal-header']}>
        <div className={styles['modal-title']}>重要业务系统投产规划信息汇总</div>
        <button className={styles['modal-close']} onClick={handleClose}>×</button>
      </div>

      <div className={styles['modal-body']}>
        {planData && (
          <>
            <PlanInfo 
              planInfo={planData.planInfo} 
              summary={summary}
              onSummaryChange={handleSummaryChange}
              loading={loading}
            />
            
            <PlanTable 
              planDetails={planData.planDetails} 
              loading={loading}
            />
          </>
        )}
      </div>

      <div className={styles['modal-footer']}>
        <ActionButtons 
          onClose={handleClose} 
          onSave={handleSave} 
          onSubmit={handleSubmit}
          loading={loading} 
        />
      </div>
    </div>
  );
};

export default Pg4;
